package megrez.boot.autoconfigure.okhttp.logging;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import lombok.extern.slf4j.Slf4j;
import megrez.boot.autoconfigure.okhttp.ApplicationInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * 日志拦截配置
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(HttpLoggingInterceptor.class)
@ConditionalOnBean(OkHttpClient.class)
@EnableConfigurationProperties(OkHttp3LoggingInterceptorProperties.class)
public class OkHttp3LoggingInterceptorAutoConfiguration {
    @Bean
    @ApplicationInterceptor
    @ConditionalOnMissingBean
    @ConditionalOnProperty(value = "okhttp.logging.enabled", havingValue = "true")
    public HttpLoggingInterceptor okHttp3LoggingInterceptor(
            OkHttp3LoggingInterceptorProperties properties,
            ObjectProvider<HttpLoggingInterceptor.Logger> logger) {

        log.info("Initializing OkHttp3LoggingInterceptor [{}]", properties);                
        HttpLoggingInterceptor.Logger actualLogger = logger.getIfUnique(() -> HttpLoggingInterceptor.Logger.DEFAULT);
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(actualLogger);
        httpLoggingInterceptor.setLevel(properties.getLevel());
        return httpLoggingInterceptor;
    }
}
